<template>
  <div class="course-detail-container">
    <div class="course-detail-box">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        <span class="breadcrumb-item" @click="goBack">首页</span>
        <span class="separator">></span>
        <span class="breadcrumb-item">{{ getCategoryName(courseForm.categoryId) }}</span>
      </div>

      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载课程信息...</p>
      </div>

      <div v-else-if="error" class="error-container">
        <i class="el-icon-error"></i>
        <p>{{ error }}</p>
        <button class="retry-btn" @click="fetchCourseDetail">重试</button>
      </div>

      <div v-else class="course-content">
        <!-- 左侧主要内容 -->
        <div class="course-main-info">
          <!-- 课程封面和播放按钮 -->
          <div class="course-cover">
            <img :src="courseForm.titleImg" :alt="courseForm.title" class="cover-image">
          </div>

          <!-- 课程标题和基本信息 -->
          <div class="course-header">
            <div class="course-type">认证学习</div>
            <h1 class="course-title">{{ courseForm.title }}</h1>
            <div class="price-section">
              <div class="price-box">
                <span class="price-symbol">￥</span>
                <span class="price-value">{{ courseForm.price || '0.00' }}</span>
              </div>
              <el-button type="primary" size="large" class="book-btn" @click="handleBookCourse">
                <i class="el-icon-date"></i>
                立即预约
              </el-button>
            </div>
            <div class="course-meta">
              <div class="meta-left">
                <span class="study-time">
                  <i class="el-icon-time"></i>
                  学时时长：{{ studyDuration }}
                </span>
                <span class="start-time">
                  <i class="el-icon-date"></i>
                  开课时间：{{ courseStartDate }}
                </span>
                <span class="repeat-type" v-if="repeatTypeText">
                  <i class="el-icon-refresh"></i>
                  重复类型：{{ repeatTypeText }}
                </span>
              </div>
              <div class="meta-right">
                <span class="share-btn">
                  <i class="el-icon-share"></i>
                  分享
                </span>
                <span class="students-count">
                  已有 {{ courseForm.studyPeople || 0 }} 人参加
                </span>
              </div>
            </div>
          </div>

          <!-- 课程功能区 -->
          <div class="course-features">
            <div class="feature-item">
              <i class="el-icon-medal"></i>
              认证成绩和证书
            </div>
            <div class="feature-item">
              <i class="el-icon-chat-dot-square"></i>
              智能问答和解析
            </div>
            <div class="feature-item">
              <i class="el-icon-video-camera"></i>
              视频学习辅助
            </div>
          </div>

          <!-- 课程详情标签页 -->
          <div class="course-tabs">
            <div class="tab-header">
              <div 
                class="tab" 
                :class="{ active: activeTab === 'details' }" 
                @click="activeTab = 'details'"
              >
                课程详情
              </div>
              <div 
                class="tab" 
                :class="{ active: activeTab === 'reviews' }" 
                @click="activeTab = 'reviews'"
              >
                课程评价
              </div>
            </div>
            <div class="tab-content">
              <!-- 课程详情内容 -->
              <div v-if="activeTab === 'details'" class="tab-pane">
                <div class="course-description markdown-content" v-html="renderMarkdown(courseForm.details)">
                </div>
                <!-- 课程内容图片展示 -->
                <div class="course-gallery" v-if="hasContentImages">
                  <h3 class="gallery-title">课程内容预览</h3>
                  <div class="gallery-grid">
                    <div v-if="courseForm.content1Img" class="gallery-item">
                      <img :src="courseForm.content1Img" alt="课程内容图片1" class="gallery-image">
                    </div>
                    <div v-if="courseForm.content2Img" class="gallery-item">
                      <img :src="courseForm.content2Img" alt="课程内容图片2" class="gallery-image">
                    </div>
                    <div v-if="courseForm.content3Img" class="gallery-item">
                      <img :src="courseForm.content3Img" alt="课程内容图片3" class="gallery-image">
                    </div>
                    <div v-if="courseForm.content4Img" class="gallery-item">
                      <img :src="courseForm.content4Img" alt="课程内容图片4" class="gallery-image">
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 课程评价内容 -->
              <div v-if="activeTab === 'reviews'" class="tab-pane">
                <!-- 课程评价列表，移除了发表评价区域 -->
                <div class="review-section">
                  <h3 class="section-title">课程评价</h3>
                  <div v-loading="loadingReviews" class="review-list">
                    <!-- 处理评论显示 -->
                    <template v-if="reviewList.length > 0">
                      <div v-for="review in reviewList" :key="review.courseReview.reviewId" class="review-item">
                        <!-- 主评论 - 移除点击事件和clickable样式 -->
                        <div class="main-review">
                          <div class="user-info">
                            <el-avatar :size="40" :src="review.userImg" />
                            <div class="user-detail">
                              <span class="user-name">{{ review.userName }}</span>
                              <el-rate v-model="review.courseReview.rating" disabled />
                            </div>
                          </div>
                          <div class="review-content">{{ review.courseReview.content }}</div>
                          <div class="review-time">{{ formatDate(review.courseReview.createdTime) }}</div>
                        </div>
                        
                        <!-- 教师回复 -->
                        <div v-if="review.courseReview.teacherReply" class="teacher-reply">
                          <div class="review-teacher-info">
                            <el-avatar :size="40" :src="review.teacherImg" />
                            <span class="teacher-name">{{ review.teacherName }}</span>
                          </div>
                          <div class="reply-content">{{ review.courseReview.teacherReply }}</div>
                          <div class="reply-time">{{ formatDate(review.courseReview.updatedTime) }}</div>
                        </div>
                      </div>
                    </template>
                    <el-empty v-else description="暂无评价信息" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧信息 -->
        <div class="course-side-info">
          <!-- 教师信息 -->
          <div class="teacher-info">
            <div class="teacher-header">
              <el-avatar :size="80" :src="teacherInfo.ossImages?.[0]?.url || '/default-avatar.png'" />
              <div class="teacher-basic">
                <h3>{{ teacherInfo.userName || '暂无名称' }}</h3>
                <div class="teacher-meta">
                  <span class="gender">{{ teacherInfo.gender === 'male' ? '男' : '女' }}</span>
                  <span class="education">{{ teacherInfo.education || '暂无学历' }}</span>
                  <span class="school">{{ teacherInfo.school || '暂无学校' }}</span>
                </div>
              </div>
            </div>
            <div class="teacher-detail">
              <div class="detail-item">
                <span class="label">教龄：</span>
                <span class="value">{{ teacherInfo.teacher?.teachingAge || 0 }}年</span>
              </div>
              <div class="detail-item">
                <span class="label">擅长科目：</span>
                <span class="value">{{ teacherInfo.teacher?.subjectArea || '暂无信息' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">教学风格：</span>
                <span class="value">{{ teacherInfo.teacher?.teachingStyle || '暂无信息' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">教师资格：</span>
                <span class="value">{{ teacherInfo.teacher?.certification || '暂无信息' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">教师评分：</span>
                <span class="value">{{ teacherInfo.teacher?.rating || 0 }}分</span>
              </div>
            </div>
            <div class="teacher-intro">
              <h4>教师简介</h4>
              <p>{{ teacherInfo.teacher?.introduction || '暂无简介' }}</p>
            </div>
          </div>

          <!-- 每日一刻 -->
          <div class="recommend-card daily-quote-card">
            <h3 class="section-title">
              <i class="el-icon-sunrise-1"></i>
              每日一刻
              <span class="today-date">{{ todayDate }}</span>
            </h3>
            <div class="daily-quote">
              <div v-if="dailyQuote" class="quote-content">
                <div class="quote-decor quote-decor-left"></div>
                <div class="quote-decor quote-decor-right"></div>
                <p>{{ dailyQuote }}</p>
                <div class="quote-footer">
                  <i class="el-icon-light-rain"></i>
                  <span class="share-quote" @click="shareQuote">
                    <i class="el-icon-share"></i>
                  </span>
                </div>
              </div>
              <p v-else-if="loadingQuote" class="loading-quote">
                <i class="el-icon-loading"></i> 加载中...
              </p>
              <p v-else class="empty-quote">
                <i class="el-icon-warning-outline"></i> 暂无推荐内容
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 学习时长信息 -->
    <div class="study-duration">
      <h3>课程信息</h3>
      <div class="duration-info">
        <div class="info-item">
          <i class="el-icon-time"></i>
          <span>单次课时：{{ studyDuration }}</span>
        </div>
        <div class="info-item">
          <i class="el-icon-date"></i>
          <span>总课时：{{ courseForm.teacherSchedule?.length || 0 }}课时</span>
        </div>
        <div class="info-item">
          <i class="el-icon-calendar"></i>
          <span>学习周期：{{ totalDays }}</span>
        </div>
      </div>
    </div>

    <!-- 课程表弹窗 -->
    <el-dialog
      title="课程预约"
      v-model="scheduleVisible"
      width="80%"
      class="schedule-dialog"
    >
      <CourseSchedule 
        :teacherAvailabilities="courseForm.teacherAvailabilities || []" 
        :teacherSchedule="courseForm.teacherSchedule || []"
        :courseTableData="courseTableData"
      />
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getCourseDetail, getTeacherInfo, getCourseTable, getCourseReviewList, getCourseReviewReplyList, insertCourseReview, replyCourseReview, getHappyRecommendations } from '@/api/course'
import { ElMessage } from 'element-plus'
import CourseSchedule from '@/components/course/CourseSchedule.vue'
import { marked } from 'marked'

/**
 * 课程详情页面组件
 * 展示课程的详细信息，包括：
 * - 课程基本信息（标题、价格、学习人数等）
 * - 教师信息
 * - 课程内容和评价
 * - 课程预约功能
 * - 每日一刻推荐
 */

export default {
  name: 'CourseDetail',
  components: {
    CourseSchedule
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const courseForm = ref({})
    const loading = ref(true)
    const error = ref('')
    const teacherInfo = ref({
      ossImages: [],
      teacher: {},
    })
    const scheduleVisible = ref(false)
    const currentWeek = ref(new Date())
    const selectedSlot = ref(null)
    const courseTableData = ref([])
    const activeTab = ref('details')
    const reviewList = ref([])
    const reviewForm = ref({
      rating: 5,
      content: '',
      courseId: null,
      bookingId: null, 
      teacherId: null,
      studentId: null
    })
    const loadingReviews = ref(false)
    const showReplyForm = ref(false)
    const replyToReviewId = ref(null)
    const replyForm = ref({
      parentId: null,
      content: '',
      rating: 5,
      courseId: null,
      bookingId: null,
      teacherId: null,
      studentId: null
    })
    const submitting = ref(false)
    const submittingReply = ref(false)
    const dailyQuote = ref('')
    const loadingQuote = ref(false)
    const todayDate = ref(new Date().toLocaleDateString('zh-CN', { month: 'long', day: 'numeric', weekday: 'long' }))

    // 判断是否有内容图片
    const hasContentImages = computed(() => {
      return courseForm.value.content1Img || 
             courseForm.value.content2Img || 
             courseForm.value.content3Img || 
             courseForm.value.content4Img
    })

    // 获取分类名称
    const getCategoryName = (categoryId) => {
      const categories = {
        1: '学术',
        2: '技术与工程',
        3: '商业与管理',
        4: '艺术与设计',
        5: '职业技能',
        6: '健康与医学',
        7: '语言与文化',
        8: '科技与未来趋势',
        9: '体育与健身'
      }
      return categories[categoryId] || `分类${categoryId}`
    }

    // 获取教师信息
    const fetchTeacherInfo = async (courseId) => {
      try {
        const response = await getTeacherInfo(courseId)
        if (response.code === 200 && response.data) {
          teacherInfo.value = {
            ...response.data,
            education: response.data.education || '',
            school: response.data.school || '',
            gender: response.data.gender || '',
            userName: response.data.userName || '',
            teacher: {
              ...response.data.teacher,
              teachingAge: response.data.teacher?.teachingAge || 0,
              subjectArea: response.data.teacher?.subjectArea || '',
              teachingStyle: response.data.teacher?.teachingStyle || '',
              certification: response.data.teacher?.certification || '',
              introduction: response.data.teacher?.introduction || '',
              rating: response.data.teacher?.rating || 0
            },
            ossImages: response.data.ossImages || []
          }
        }
      } catch (err) {
        ElMessage.error('获取教师信息失败')
        // 发生错误时设置默认值
        teacherInfo.value = {
          ossImages: [],
          teacher: {},
          education: '',
          school: '',
          gender: '',
          userName: ''
        }
      }
    }

    // 获取课程详情
    const fetchCourseDetail = async () => {
      const courseId = route.params.id
      
      if (!courseId) {
        error.value = '课程ID不能为空'
        loading.value = false
        return
      }

      // 确保courseId是字符串类型
      const courseIdStr = String(courseId)
      
      loading.value = true
      error.value = ''
      
      try {
        const response = await getCourseDetail(courseIdStr)
        
        if (response.code === 200 && response.data) {
          courseForm.value = response.data
          
          // 处理课程时间安排
          if (courseForm.value.teacherSchedule && courseForm.value.teacherSchedule.length > 0) {
            // 按日期降序排序，最新的排在前面
            courseForm.value.teacherSchedule.sort((a, b) => {
              const dateA = new Date(a.date);
              const dateB = new Date(b.date);
              return dateB - dateA; // 降序排列
            });
          }
          
          // 获取教师信息
          await fetchTeacherInfo(courseIdStr)
        } else {
          error.value = response.message || '获取课程详情失败'
        }
      } catch (err) {
        error.value = '获取课程详情失败: ' + (err.message || '服务器错误')
      } finally {
        loading.value = false
      }
    }

    // 处理预约课程
    const handleBookCourse = async () => {
      // 检查用户是否已登录
      const token = sessionStorage.getItem('token') || localStorage.getItem('token')
      if (!token) {
        ElMessage.warning('请先登录后再预约课程')
        router.push('/login')
        return
      }

      try {
        // 获取课程表数据，使用route.params.id作为courseId
        const response = await getCourseTable(route.params.id)
        if (response.code === 200 && response.data) {
          courseTableData.value = response.data
          // 显示预约弹窗
          scheduleVisible.value = true
        } else {
          ElMessage.error(response.message || '获取课程表失败')
        }
      } catch (err) {
        console.error('获取课程表失败:', err)
        ElMessage.error('获取课程表失败')
      }
    }

    // 返回上一页
    const goBack = () => {
      router.back()
    }

    // 生成周时间表
    const weekSchedule = computed(() => {
      return [
        { time: '09:00-10:00' },
        { time: '10:00-11:00' },
        { time: '11:00-12:00' },
        { time: '14:00-15:00' },
        { time: '15:00-16:00' },
        { time: '16:00-17:00' },
      ]
    })

    // 获取本周日期
    const weekDays = computed(() => {
      const days = []
      const curr = new Date(currentWeek.value)
      const first = curr.getDate() - curr.getDay()
      
      for(let i = 0; i < 7; i++) {
        const day = new Date(curr.setDate(first + i))
        days.push({
          date: day.toISOString().split('T')[0],
          label: `${day.getMonth() + 1}月${day.getDate()}日`
        })
      }
      return days
    })

    // 计算学习时长
    const studyDuration = computed(() => {
      if (!courseForm.value?.teacherSchedule || courseForm.value.teacherSchedule.length === 0) {
        return '暂无数据';
      }
      
      const firstSchedule = courseForm.value.teacherSchedule[0];
      if (!firstSchedule.startTime || !firstSchedule.endTime) {
        return '暂无数据';
      }
      
      try {
        const startTime = new Date(`2000-01-01 ${firstSchedule.startTime}`);
        const endTime = new Date(`2000-01-01 ${firstSchedule.endTime}`);
        
        // 计算时间差（毫秒）
        const diffMs = endTime - startTime;
        
        // 将毫秒转换为小时和分钟
        const hours = Math.floor(diffMs / (1000 * 60 * 60));
        const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
        
        if (hours === 0) {
          return `${minutes}分钟`;
        } else if (minutes === 0) {
          return `${hours}小时`;
        } else {
          return `${hours}小时${minutes}分钟`;
        }
      } catch (error) {
        ElMessage.error('计算学习时长出错')
        return '暂无数据';
      }
    });

    const courseStartDate = computed(() => {
      if (!courseForm.value?.teacherSchedule || courseForm.value.teacherSchedule.length === 0) {
        return '暂无数据';
      }
      
      const firstSchedule = courseForm.value.teacherSchedule[0];
      if (!firstSchedule.date) {
        return '暂无数据';
      }
      
      let displayText = firstSchedule.date;
      
      // 如果有开始时间，则添加
      if (firstSchedule.startTime) {
        displayText += ` ${firstSchedule.startTime.substring(0, 5)}`;
      }
      
      return displayText;
    });

    const repeatTypeText = computed(() => {
      if (!courseForm.value?.teacherSchedule || courseForm.value.teacherSchedule.length === 0) {
        return '';
      }
      
      const firstSchedule = courseForm.value.teacherSchedule[0];
      if (!firstSchedule.repeatType) {
        return '';
      }
      
      const repeatTypeMap = {
        'once': '一次性',
        'daily': '每天',
        'weekly': '每周',
        'biweekly': '每两周',
        'monthly': '每月'
      };
      
      return repeatTypeMap[firstSchedule.repeatType] || firstSchedule.repeatType;
    });

    // 计算学习周期
    const studyPeriod = computed(() => {
      if (!courseForm.value?.teacherSchedule || courseForm.value.teacherSchedule.length === 0) {
        return '暂无数据';
      }
      
      const schedules = [...courseForm.value.teacherSchedule];
      
      // 按日期排序
      schedules.sort((a, b) => {
        return new Date(a.date) - new Date(b.date);
      });
      
      const startDate = schedules[0].date;
      
      // 如果是一次性课程
      if (schedules.length === 1 || schedules[0].repeatType === 'once') {
        return `${startDate} (一次性)`;
      }
      
      // 如果有多次课程
      const endDate = schedules[schedules.length - 1].date;
      
      // 如果有重复类型，显示重复信息
      if (schedules[0].repeatType && schedules[0].repeatType !== 'once') {
        const repeatTypeMap = {
          'daily': '每天',
          'weekly': '每周',
          'biweekly': '每两周',
          'monthly': '每月'
        };
        
        return `${startDate} 至 ${endDate} (${repeatTypeMap[schedules[0].repeatType] || schedules[0].repeatType})`;
      }
      
      // 默认显示日期范围
      return `${startDate} 至 ${endDate}`;
    });

    // 计算学习周期总天数
    const totalDays = computed(() => {
      if (!courseForm.value?.teacherSchedule || courseForm.value.teacherSchedule.length === 0) {
        return '暂无数据';
      }
      
      // 如果只有一节课，周期为0天
      if (courseForm.value.teacherSchedule.length === 1) {
        return '单日课程';
      }
      
      const schedules = [...courseForm.value.teacherSchedule];
      
      // 按日期排序
      schedules.sort((a, b) => {
        return new Date(a.date) - new Date(b.date);
      });
      
      const firstDate = new Date(schedules[0].date);
      const lastDate = new Date(schedules[schedules.length - 1].date);
      
      // 计算天数差异
      const diffTime = Math.abs(lastDate - firstDate);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      
      return diffDays === 0 ? '单日课程' : `${diffDays}天`;
    });

    // 获取课程评价
    const fetchReviews = async () => {
      loadingReviews.value = true
      try {
        if (!route.params.id) {
          ElMessage.warning('课程ID不能为空')
          return
        }
        
        const response = await getCourseReviewList(route.params.id)
        if (response.code === 200) {
          reviewList.value = response.data
        } else {
          ElMessage.error('获取课程评价失败：' + response.message)
        }
      } catch (err) {
        ElMessage.error('获取课程评价失败: ' + (err.message || '服务器错误'))
      } finally {
        loadingReviews.value = false
      }
    }

    // 获取格式化后的课程评价
    const getFormattedReviews = () => {
      return reviewList.value.map(review => ({
        ...review,
        repliesLoaded: false,
        replies: []
      }))
    }

    // 加载评论回复
    const loadReviewReplies = async (reviewId) => {
      const review = reviewList.value.find(r => r.courseReview.reviewId === reviewId)
      if (review && !review.repliesLoaded) {
        try {
          const response = await getCourseReviewReplyList(reviewId)
          if (response.code === 200) {
            // 更新reviewList中的回复
            const updatedReviewList = JSON.parse(JSON.stringify(reviewList.value))
            const index = updatedReviewList.findIndex(r => r.courseReview.reviewId === reviewId)
            if (index !== -1) {
              updatedReviewList[index].repliesLoaded = true
              updatedReviewList[index].replies = response.data
              reviewList.value = updatedReviewList
            }
          } else {
            ElMessage.error('获取评论回复失败：' + response.message)
          }
        } catch (err) {
          console.error('获取评论回复失败:', err)
          ElMessage.error('获取评论回复失败: ' + (err.message || '服务器错误'))
        }
      }
    }

    // 打开回复表单
    const openReplyForm = (reviewId, event) => {
      event.stopPropagation()
      replyToReviewId.value = reviewId
      showReplyForm.value = true
    }

    // 取消回复
    const cancelReply = () => {
      showReplyForm.value = false
      replyToReviewId.value = null
    }

    // 提交回复
    const submitReply = async (reviewId) => {
      if (!replyForm.value.content || replyForm.value.content.trim() === '') {
        ElMessage.warning('回复内容不能为空')
        return
      }
      
      submittingReply.value = true
      try {
        // 设置父评论ID和课程ID
        replyForm.value.parentId = reviewId
        replyForm.value.courseId = route.params.id

        const response = await replyCourseReview(replyForm.value)
        if (response.code === 200) {
          ElMessage.success('回复成功')
          // 关闭回复表单
          showReplyForm.value = false
          replyToReviewId.value = null
          replyForm.value.content = ''
          
          // 重新加载评论列表
          await fetchReviews()
        } else {
          ElMessage.error('回复失败：' + response.message)
        }
      } catch (err) {
        console.error('回复失败:', err)
        ElMessage.error('回复失败: ' + (err.message || '服务器错误'))
      } finally {
        submittingReply.value = false
      }
    }

    // 提交新评论
    const submitReview = async () => {
      if (!reviewForm.value.content || reviewForm.value.content.trim() === '') {
        ElMessage.warning('评价内容不能为空')
        return
      }
      
      submitting.value = true
      try {
        // 设置课程ID
        reviewForm.value.courseId = route.params.id
        
        const response = await insertCourseReview(reviewForm.value)
        if (response.code === 200) {
          ElMessage.success('评价发表成功')
          // 清空评价内容，保留评分
          reviewForm.value.content = ''
          
          // 重新加载评论列表
          await fetchReviews()
        } else {
          ElMessage.error('评价发表失败：' + response.message)
        }
      } catch (err) {
        console.error('评价发表失败:', err)
        ElMessage.error('评价发表失败: ' + (err.message || '服务器错误'))
      } finally {
        submitting.value = false
      }
    }

    // 添加监听activeTab变化的逻辑
    watch(activeTab, (newVal) => {
      if (newVal === 'reviews') {
        // 当切换到评价标签页时，加载评论列表
        fetchReviews()
      }
    })

    // 添加formatDate函数到return中
    const formatDate = (timestamp) => {
      const date = new Date(timestamp)
      return date.toLocaleString()
    }

    /**
     * 获取每日一刻推荐
     * 从服务器获取每日推荐内容，用于展示在右侧栏
     */
    const fetchDailyQuote = async () => {
      loadingQuote.value = true
      try {
        const response = await getHappyRecommendations()
        if (response.code === 200) {
          dailyQuote.value = response.data
        } else {
          ElMessage.error('获取每日一刻推荐失败：' + response.message)
        }
      } catch (err) {
        ElMessage.error('获取每日一刻推荐失败：' + (err.message || '服务器错误'))
      } finally {
        loadingQuote.value = false
      }
    }

    /**
     * 分享每日一刻内容
     * 将当前显示的每日一刻内容复制到剪贴板
     */
    const shareQuote = () => {
      if (dailyQuote.value) {
        try {
          navigator.clipboard.writeText(dailyQuote.value)
          ElMessage.success('内容已复制到剪贴板')
        } catch (err) {
          ElMessage.error('复制失败，请手动复制')
        }
      }
    }

    /**
     * 渲染Markdown内容
     * @param {string} content - Markdown格式的内容
     * @returns {string} 渲染后的HTML内容
     */
    const renderMarkdown = (content) => {
      if (!content) return '';
      try {
        return marked(content);
      } catch (error) {
        ElMessage.error('Markdown渲染错误：' + (error.message || '未知错误'));
        return content;
      }
    };

    onMounted(() => {
      fetchCourseDetail()
      fetchDailyQuote()
    })

    return {
      courseForm,
      loading,
      error,
      teacherInfo,
      scheduleVisible,
      selectedSlot,
      weekSchedule,
      weekDays,
      hasContentImages,
      studyDuration,
      courseStartDate,
      repeatTypeText,
      getCategoryName,
      fetchCourseDetail,
      goBack,
      handleBookCourse,
      studyPeriod,
      totalDays,
      courseTableData,
      activeTab,
      reviewList,
      reviewForm,
      loadingReviews,
      showReplyForm,
      replyToReviewId,
      replyForm,
      submitting,
      submittingReply,
      fetchReviews,
      getFormattedReviews,
      loadReviewReplies,
      openReplyForm,
      cancelReply,
      submitReply,
      submitReview,
      formatDate,
      dailyQuote,
      loadingQuote,
      todayDate,
      shareQuote,
      renderMarkdown
    }
  }
}
</script>

<style scoped>
.course-detail-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.course-detail-box {
  max-width: 1400px;  /* 增加容器宽度以适应更大的图片 */
  margin: 0 auto;
}

.breadcrumb {
  padding: 15px 0;
  color: #666;
  font-size: 14px;
}

.breadcrumb-item {
  cursor: pointer;
}

.breadcrumb-item:hover {
  color: #409EFF;
}

.separator {
  margin: 0 8px;
  color: #999;
}

.course-content {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 20px;
}

.course-main-info {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.course-cover {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 比例 */
}

.cover-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.course-header {
  padding: 20px;
}

.course-type {
  display: inline-block;
  padding: 4px 12px;
  background: #fff3e6;
  color: #ff9900;
  border-radius: 4px;
  font-size: 14px;
  margin-bottom: 15px;
}

.course-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
}

.price-section {
  margin: 20px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.price-box {
  display: flex;
  align-items: baseline;
}

.price-symbol {
  color: #ff4d4f;
  font-size: 24px;
  font-weight: 600;
  margin-right: 4px;
}

.price-value {
  color: #ff4d4f;
  font-size: 38px;
  font-weight: 700;
  line-height: 1;
}

.book-btn {
  padding: 0 35px;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 24px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.book-btn i {
  font-size: 18px;
}

.course-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.meta-left {
  display: flex;
  gap: 20px;
}

.meta-right {
  display: flex;
  gap: 15px;
}

.course-features {
  display: flex;
  padding: 15px 20px;
  background: #fafafa;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.feature-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.feature-item i {
  color: #409EFF;
}

.course-tabs {
  padding: 20px;
}

.tab-header {
  display: flex;
  gap: 30px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.tab {
  padding: 10px 0;
  color: #666;
  cursor: pointer;
  position: relative;
}

.tab.active {
  color: #409EFF;
  font-weight: 500;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background: #409EFF;
}

.course-description {
  color: #666;
  line-height: 1.8;
  margin-bottom: 30px;
}

.course-gallery {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 30px;
}

.gallery-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20px;
}

.gallery-grid {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.gallery-item {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  margin: 0 auto;
}

.gallery-image {
  width: 100%;
  height: auto;
  max-width: 100%;
  object-fit: contain;
  transition: transform 0.3s;
}

.gallery-item:hover .gallery-image {
  transform: scale(1.05);
}

.course-side-info {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.teacher-card, .recommend-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.teacher-list, .recommend-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.teacher-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.teacher-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.teacher-info {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.teacher-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.teacher-basic {
  flex: 1;
}

.teacher-basic h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #333;
}

.teacher-meta {
  display: flex;
  gap: 15px;
  color: #666;
  font-size: 14px;
}

.teacher-detail {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
  font-size: 14px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  color: #666;
  width: 100px;
}

.detail-item .value {
  color: #333;
  flex: 1;
}

.teacher-intro {
  margin-top: 20px;
}

.teacher-intro h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.teacher-intro p {
  margin: 0;
  color: #666;
  line-height: 1.6;
  font-size: 14px;
}

.recommend-item {
  display: flex;
  gap: 10px;
}

.recommend-thumb {
  width: 80px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
}

.recommend-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.recommend-title {
  font-size: 14px;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.recommend-count {
  font-size: 12px;
  color: #999;
}

.daily-quote-card {
  overflow: hidden;
  position: relative;
}

.today-date {
  font-size: 13px;
  color: #909399;
  font-weight: normal;
  margin-left: auto;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.daily-quote {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
  padding: 30px 25px;
  margin-top: 15px;
  font-size: 16px;
  color: #333;
  line-height: 1.8;
  text-align: center;
  font-style: italic;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
  transition: all 0.3s ease;
  overflow: hidden;
}

.daily-quote:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 25px rgba(0, 0, 0, 0.1);
}

.daily-quote::before,
.daily-quote::after {
  content: '"';
  font-size: 60px;
  font-family: serif;
  color: rgba(64, 158, 255, 0.1);
  position: absolute;
  line-height: 1;
}

.daily-quote::before {
  top: 10px;
  left: 15px;
}

.daily-quote::after {
  bottom: -15px;
  right: 15px;
}

.quote-decor {
  position: absolute;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: radial-gradient(circle, rgba(64, 158, 255, 0.05) 0%, rgba(255, 255, 255, 0) 70%);
  z-index: 0;
}

.quote-decor-left {
  top: -20px;
  left: -20px;
}

.quote-decor-right {
  bottom: -20px;
  right: -20px;
}

.daily-quote p {
  margin: 0;
  padding: 15px 25px;
  position: relative;
  z-index: 1;
  letter-spacing: 0.5px;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.quote-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.quote-footer {
  margin-top: 15px;
  font-size: 20px;
  color: rgba(64, 158, 255, 0.6);
  display: flex;
  justify-content: center;
  gap: 15px;
}

.quote-footer i {
  opacity: 0.7;
  transition: all 0.3s ease;
  cursor: pointer;
}

.quote-footer i:hover {
  opacity: 1;
  transform: scale(1.2);
  color: #409EFF;
}

.share-quote {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.loading-quote {
  color: #909399;
  text-align: center;
  padding: 30px;
  font-size: 14px;
  animation: pulse 1.5s infinite ease-in-out;
}

@keyframes pulse {
  0% { opacity: 0.5; }
  50% { opacity: 1; }
  100% { opacity: 0.5; }
}

.empty-quote {
  color: #909399;
  text-align: center;
  padding: 30px;
  font-size: 14px;
}

@media (max-width: 1400px) {
  .gallery-item {
    width: 100%;
  }

  .gallery-image {
    width: 100%;
    height: calc((100vw - 40px) * 0.54); /* 保持宽高比 */
  }
}

@media screen and (max-width: 1200px) {
  .course-detail-box {
    padding: 0 15px;
  }
}

@media screen and (max-width: 992px) {
  .course-content {
    grid-template-columns: 1fr;
  }
  
  .course-side-info {
    order: -1;
  }
}

@media screen and (max-width: 768px) {
  .course-detail-container {
    padding: 10px;
  }
  
  .course-header {
    padding: 15px;
  }
  
  .course-meta {
    flex-direction: column;
    gap: 10px;
  }
  
  .course-features {
    flex-direction: column;
    gap: 10px;
  }
  
  .course-title {
    font-size: 20px;
  }
  
  .price-box .price-value {
    font-size: 28px;
  }
  
  .book-btn {
    padding: 0 20px;
    height: 40px;
    font-size: 14px;
  }
}

.study-duration {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.duration-info {
  display: flex;
  gap: 30px;
  margin-top: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.info-item i {
  color: #409EFF;
}

.calendar-wrapper {
  padding: 20px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.booked {
  color: #999;
  font-size: 13px;
}

/* 课程评价相关样式 */
.rating-container {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.rating-label {
  margin-right: 8px;
  font-size: 14px;
  color: #606266;
}

.review-textarea {
  margin-bottom: 16px;
}

.review-actions {
  display: flex;
  justify-content: flex-end;
}

.review-section {
  margin-top: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 20px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.review-list {
  margin-top: 20px;
}

.review-item {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.main-review {
  cursor: pointer;
}

.main-review.clickable:hover {
  background-color: #f5f7fa;
  transform: translateY(-2px);
  transition: all 0.3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-weight: 500;
  color: #303133;
}

.review-content {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.review-time {
  font-size: 12px;
  color: #909399;
}

.click-hint {
  margin-left: 8px;
  color: #409eff;
}

.teacher-reply {
  margin-top: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.review-teacher-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.reply-list {
  margin-top: 16px;
  margin-left: 40px;
}

.reply-item {
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 10px;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.reply-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.reply-user {
  font-weight: 500;
  color: #303133;
}

.reply-content {
  color: #606266;
  line-height: 1.6;
}

.reply-time {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.reply-form {
  margin-top: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.reply-form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 12px;
}

/* Markdown内容样式 */
.markdown-content {
  line-height: 1.6;
  color: #333;
}

.markdown-content :deep(h1) {
  font-size: 1.8em;
  margin-top: 1em;
  margin-bottom: 0.5em;
  font-weight: 600;
}

.markdown-content :deep(h2) {
  font-size: 1.5em;
  margin-top: 1em;
  margin-bottom: 0.5em;
  font-weight: 600;
}

.markdown-content :deep(h3) {
  font-size: 1.3em;
  margin-top: 1em;
  margin-bottom: 0.5em;
  font-weight: 600;
}

.markdown-content :deep(p) {
  margin-bottom: 1em;
}

.markdown-content :deep(ul), .markdown-content :deep(ol) {
  margin-bottom: 1em;
  padding-left: 2em;
}

.markdown-content :deep(li) {
  margin-bottom: 0.5em;
}

.markdown-content :deep(code) {
  background-color: #f5f5f5;
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-family: monospace;
}

.markdown-content :deep(pre) {
  background-color: #f5f5f5;
  padding: 1em;
  border-radius: 5px;
  overflow-x: auto;
  margin-bottom: 1em;
}

.markdown-content :deep(blockquote) {
  border-left: 4px solid #ddd;
  padding-left: 1em;
  margin-left: 0;
  color: #666;
}

.markdown-content :deep(a) {
  color: #1890ff;
  text-decoration: none;
}

.markdown-content :deep(a:hover) {
  text-decoration: underline;
}

.markdown-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 5px;
  margin: 1em 0;
}

.markdown-content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 1em;
}

.markdown-content :deep(th), .markdown-content :deep(td) {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.markdown-content :deep(th) {
  background-color: #f5f5f5;
}
</style> 